﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;

namespace CompanyManagement.Models
{
    public class WardDAO
    {
        CompanyEntities db;
        public WardDAO()
        {
            db = new CompanyEntities();
        }

        public List<Ward> GetWardsByDistrictCode(string districtCode)
        {
            var district = db.Districts.FirstOrDefault(p => p.Code.Equals(districtCode));
            var districtID = district == null ? -1: district.ID;
            return db.Wards.Where(p => p.IsActive == true && p.DistrictID == districtID).ToList();
        }

        public List<Ward> GetWards()
        {
            return db.Wards.Where(p => p.IsActive == true).ToList();
        }

        public bool Insert(Ward ward)
        {
            try
            {
                db.Wards.Add(ward);
                db.SaveChanges();
                return true;
            }
            catch (Exception)
            {
                throw;
            }
        }

        public bool Delete(Ward deleteObj)
        {
            try
            {
                var ward = db.Wards.FirstOrDefault(p => p.ID == deleteObj.ID && p.IsActive == true);
                if (ward != null)
                {
                    ward.IsActive = false;
                    db.SaveChanges();
                    return true;
                }
                return false;
            }
            catch (Exception)
            {
                throw;
            }
        }

        internal bool CheckWardInUse(Ward deleteObj)
        {
            var ward = db.Wards.FirstOrDefault(p => p.ID == deleteObj.ID && p.IsActive == true);
            if (ward != null)
            {
                return db.Companies.Any(p => p.WardCode.Equals(ward.Code) && p.IsActive == true);
            }
            return false;
        }

        internal bool CheckWardExisted(Ward insertObj)
        {
            return db.Wards.Any(p => p.ID != insertObj.ID && p.IsActive == true && (p.Code.Equals(insertObj.Code) || p.Name.Equals(insertObj.Name)));
        }

        internal Ward GetWardByID(int id)
        {
            return db.Wards.FirstOrDefault(p => p.ID == id && p.IsActive == true);
        }

        internal bool Update(Ward updateObj)
        {
            try
            {
                var ward = db.Wards.FirstOrDefault(p => p.ID == updateObj.ID && p.IsActive == true);
                if (ward != null)
                {
                    ward.Name = updateObj.Name;
                    ward.DistrictID = updateObj.DistrictID;

                    db.SaveChanges();
                    return true;
                }
                return false;
            }
            catch (Exception)
            {
                throw;
            }
        }
    }
}